package com.gw.controller;

import com.gw.pojo.dto.UserForgetPasswordDTO;
import com.gw.pojo.dto.UserLoginDTO;
import com.gw.pojo.dto.UserRegisterDTO;
import com.gw.pojo.vo.UserLoginVO;
import com.gw.result.Result;
import com.gw.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    // 定义邮箱格式的正则表达式
    private static final String EMAIL_REGEX = "^[\\w!#$%&'*+/=?`{|}~^.-]+@[\\w.-]+\\.[a-zA-Z]{2,}$";

    private static final String PHONE_REGEX = "^13[0-9]\\d{8}$|^14(5|7)\\d{8}$|^15\\d{9}$|^16(2|5|6|7)\\d{8}$|^17([0-3]|[5-8])\\d{8}$|^18\\d{9}$|^19(1|8|9)\\d{8}$|^09\\d{8}$|^(5|6|8|9)\\d{7}$|^6(6|8)\\d{6}$\n";

    // 编译正则表达式
    private static final Pattern EMAIL_PATTERN = Pattern.compile(EMAIL_REGEX);
    private static final Pattern PHONE_PATTERN = Pattern.compile(PHONE_REGEX);

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * @param loginDTO
     * @param result
     * @return
     */
    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody @Validated UserLoginDTO loginDTO, BindingResult result) {
        log.info("用户登录验证图形验证码：{}",loginDTO.toString());
        if (result.hasErrors()) {
            return Result.error("信息输入不正确");
        }
        //获取uuid
        String uuid = loginDTO.getUuid();
        //获取验证码
        String code = loginDTO.getCode();
        //验证验证码是否正确
        if (!Objects.equals(redisTemplate.opsForValue().get(uuid), code)) {
            log.info("判断结果{}",!Objects.equals(redisTemplate.opsForValue().get(uuid), code));
            //错误则返回前端并提示
            return Result.error("验证码错误，请重新验证");
        }

        //验证成功则清除redis内的验证码缓存
        redisTemplate.delete(uuid);

        log.info("用户登录{}", loginDTO);
        UserLoginVO userLoginVO = userService.login(loginDTO);
        return Result.success(userLoginVO);
    }

    /**
     * 获取验证码
     *
     * @return
     */
    @GetMapping("/getCode")
    public Result<Map<String, String>> getCode() {
        log.info("获取图形验证码...");
        //TODO 将图形验证码写到前端（待解决）
        ConcurrentHashMap<String, String> map = userService.getCode();

        return Result.success(map);
    }


    /**
     * 用户注册
     * @param userRegisterDTO
     * @param result
     * @return
     */
    @PostMapping("/register")
    public Result<UserLoginVO> register(@RequestBody @Validated UserRegisterDTO userRegisterDTO, BindingResult result){
        log.info("新用户注册...");
        if (result.hasErrors()) {
            return Result.error("信息输入不正确!");
        }

        UserLoginVO userLoginVO = userService.register(userRegisterDTO);

        return Result.success(userLoginVO);
    }


    /**
     * 发送邮箱验证码
     * @param email
     * @return
     */
    @GetMapping("/sendCode/{email}")
    public Result sendCode(@PathVariable String email){
        //判断邮箱格式
        if (email == null) {
            return Result.error("邮箱为空");
        }
        Matcher matcher = EMAIL_PATTERN.matcher(email);
        if (!matcher.matches()) {
            return Result.error("邮箱格式错误");
        }

        log.info("发送邮箱验证码...");
        userService.sendCode(email);
        return Result.success();
    }

    /**
     * 忘记密码
     * @param userForgetPasswordDTO
     * @return
     */
    @PostMapping("/forget")
    public Result forgetPassword(@RequestBody @Validated UserForgetPasswordDTO userForgetPasswordDTO,
                                              BindingResult result){

        if (result.hasErrors()) {
            return Result.error("传入信息有误,请重新输入！");
        }

        userService.forgetPassword(userForgetPasswordDTO);


        return Result.success();
    }

    /**
     * 退出登录
     * @return
     */
    @PostMapping("/logout")
    public Result logout(){return Result.success();}


}
